package com.xncoding.pos.nacos;

import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executor;

/**
 * nacos配置类---适合解析和监听json内容的配置,yml类型的也可以
 *
 * @Author guoyb
 * @Date 2020/11/30  9:55
 */
@Slf4j
public abstract class BaseNacosConfig {

    /**
     * 系统初始化加载
     *
     * @param dataId
     * @param group
     * @throws NacosException
     */
    protected void init(ConfigService configService, final String dataId, String group) throws NacosException {
        String config = configService.getConfig(dataId, group, 3000);
        log.info("获取配置-----打印日志------{}", config);

        configService.addListener(dataId, group, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                log.info("监听配置--------------Listener:receiveConfigInfo-----:{}", configInfo);
                parseConfig(configInfo);
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });

        parseConfig(config);
    }

    /**
     * 将json赋值
     *
     * @param config
     */
    protected abstract void parseConfig(String config);

    /**
     * 向nacos发布内容
     *
     * @param content 内容
     * @throws Exception 异常
     */
    public void publishConfig(ConfigService configService,String content, final String dataId, String groupId) throws Exception {
        //发布内容
        configService.publishConfig(dataId, groupId, content);
    }
}
